// import type { Plugin } from 'vue'
import { createApp } from 'vue'

import loadingComponent from '@/components/Loading/index.vue'

const loadings: Array<{
  el: HTMLDivElement
  instance: any
}> = []

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use({
    install: (app) => {
      const appConfig = app.config.globalProperties

      appConfig.$showLoading = (): void => {
        // const ocLoading = document.getElementById('oc-loading')
        // if(!ocLoading) {
        //   const el = document.createElement('div');
        //   el.setAttribute('id', 'oc-loading');
        //   document.body.appendChild(el);
        // }
        if (loadings.length !== 0) return
        const instance = createApp(loadingComponent)
        const div = document.createElement('div')
        div.setAttribute('id', 'oc-loading')
        instance.provide('page-data', {})
        instance.mount(div)
        document.body?.appendChild(div)
        loadings.push({
          el: div,
          instance,
        })
      }
      appConfig.$closeLoading = (delta: number = 1): void => {
        if (delta < 0) {
          // getApp().$back(delta);
          delta = loadings.length
        }
        if (loadings.length) {
          for (let i = 0; i < delta; i++) {
            const item = loadings[loadings.length - 1]
            document.body?.removeChild(item.el)
            item.instance.unmount()
            loadings.splice(loadings.length - 1, 1)
          }
        }
      }
    },
  })
})
